﻿using System.Diagnostics;
using System.IO.Ports;
using System.Text;
using TouchSocket.Core;
using TouchSocket.SerialPorts;
using TouchSocket.Sockets;

namespace Om.Core.Device;

public class SignalGenerator
{
    public SerialPortClient Client = new SerialPortClient();
    private IWaitingClient<ISerialPortClient, IReceiverResult> _spWaitClient = null;

    public async Task Connect(string com)
    {
        if (Client.Online) return;

        Client.Setup(new TouchSocketConfig()
            .SetSerialPortOption(new SerialPortOption()
            {
                PortName = com,
                BaudRate = 115200,
                DataBits = 8,
                Parity = Parity.None,
                StopBits = StopBits.One
            }));

        _spWaitClient = Client.CreateWaitingClient(new WaitingOptions()
        {
            FilterFunc = response =>
            {
                var isTrue = response.ByteBlock.Length > 0;
                return isTrue;
            }
        });
        var res = await Client.TryConnectAsync();
        if (!res.IsSuccess)
            throw new Exception(res.Message);
    }


    public async Task Disconnect()
    {
        await Client.SafeCloseAsync();
    }

    public async Task<bool> StartSendSignal(int ms)
    {
        ms = Math.Min(4000, ms);
        var cmd = $"AT+GPDO=ALL,{ms},10,0\r\n";
        var result = await _spWaitClient.SendThenReturnAsync(cmd);
        var msg = Encoding.UTF8.GetString(result);
        if (msg.ToLower().EndsWith("ok!"))
            return true;
        return false;
    }
    public async Task<bool> StopSendSignal()
    {
        var cmd = $"AT+GPDO=ALL,0,10,0\r\n";
        var result = await _spWaitClient.SendThenReturnAsync(cmd);
        var msg = Encoding.UTF8.GetString(result);
        if (msg.ToLower().EndsWith("ok!"))
            return true;
        return false;
    }
}